<?php
class ApiResponse
{
    /**
     * 返回成功的响应
     *
     * @param mixed $data 响应数据
     * @param int $statusCode HTTP状态码，默认200
     * @return void
     */
    public static function success($data, $statusCode = 200)
    {
        self::respond(['success' => true, 'data' => $data], $statusCode);
    }

    /**
     * 返回失败的响应
     *
     * @param string $errorMessage 错误消息
     * @param int $statusCode HTTP状态码，默认500
     * @return void
     */
    public static function error($errorMessage, $statusCode = 500)
    {
        self::respond(['success' => false, 'error' => $errorMessage], $statusCode);
    }

    /**
     * 构建并输出响应
     *
     * @param array $response 响应数据
     * @param int $statusCode HTTP状态码
     * @return void
     */
    private static function respond($response, $statusCode)
    {
        // 设置HTTP状态码
        http_response_code($statusCode);

        // 输出JSON响应
        header('Content-Type: application/json');
        echo json_encode($response);
    }
}
?>